package org.video.helloworld;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import org.video.helloworld.fixUtil.BugClass;
import org.video.helloworld.fixUtil.FixDexUtil;

import java.io.File;

import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    private Context context;
    private TextView tvMsg;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        button = findViewById(R.id.but_bug);
        tvMsg = findViewById(R.id.tv_msg);
        if (Build.VERSION.SDK_INT>21) {
            permission();
        }else {
            init();
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                init();
                new BugClass(context);
            }
        });
    }

    @SuppressLint("CheckResult")
    private void permission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            Toast.makeText(context,"允许了权限",Toast.LENGTH_SHORT).show();
                            init();
                        }
                    }
                });
    }

    private void init(){
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        //遍历所有的修复dex,可能多个丢夫包
        File fileDir = externalStorageDirectory!=null?
                new File(externalStorageDirectory,"007"):
                new File(getFilesDir(), FixDexUtil.DEX_DIR);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        if (FixDexUtil.isGoingToFix(this)){
            FixDexUtil.loadFixedDex(this,Environment.getExternalStorageDirectory());
            tvMsg.setText("正在修复bug...");
        }
    }
}